package com.qikux.utils;

import cn.hutool.extra.mail.MailUtil;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class SendMailUtils {
    /**
     * 发送 激活账户的邮件
     * @param tel :  激活的账户名
     * @param userId  : 激活的用户ID
     * @param email : 收件邮箱
     */
    public static void sendMailForActiveAccount(String tel, Long userId, String email) {

        long minus = 10 ;
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(minus);
        String _lastTime = localDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));

        String lastTime = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        // 这个字符串中的任何数据不允许被篡改
        String message = "u=" + userId + "&t=" + _lastTime;

        String sign = RSAUtils.sign(message);

        HttpServletRequest request = ContextUtils.getRequest() ;

        String linkUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath() + "/user/active?u=" + userId + "&t=" + _lastTime + "&sign=" + sign;

        // 设置邮件的内容
        String content = """
                <p>尊敬的先生/女士:</p>
                <p>账号<b style="color:red">%s</b>已注册成功,有效期为%s分钟，请您与%s之前点击下方的链接激活该账号</p>     
                <p><a href="%s">%s</a></p>
                <p>如非您本人操作、请忽略该邮件即可！</p>
                """ ;

        // 邮件正文内容
        content = content.formatted(tel, minus, lastTime, linkUrl, linkUrl);
        // 发送邮件  设置邮件的主题
        MailUtil.send(email, "Haredot-账户激活", content, true);

    }
}
